import { Version } from '../components/index.js'

async function fix(str, e) {
    // 如果输入为空或者不包含数字，直接返回原字符串
    if (!str || !/\d/.test(str)) {
        str = str.slice(1, -1)
        return str
    }
    // 声明一个数组，用来存放匹配到的数字
    let nums = []
    // 声明一个数组，用来存放对应的昵称
    let names = []
    // 声明一个变量，用来存放替换后的字符串
    let name
    let index = 0
    // 用正则表达式匹配字符串中的8位以上的数字，并把它们替换成AAAA
    str = str.replace(/\d{8,}/g, (match) => {
        nums.push(match)
        return 'AAAA'
    })
    try {
        names = await Promise.all(nums.map(async (qq) => {
            if (qq == (e.sender?.user_id || e.user_id)) return name = e.sender?.card || (e.sender?.nickname || e.nickname) || qq
            if (qq == e.at && Version.isTrss && e.bot?.adapter?.name == 'chronocat') {
                let ntqqatName = await e.bot.pickMember(e.group_id, e.at)
                return name = ntqqatName?.info?.card || ntqqatName?.info?.nickname || qq
            }
            let member
            try {
                member = await Bot.getGroupMemberInfo(e.group_id, qq)
            } catch (err) {
                console.log("错误:", err)
            }
            member = typeof member === "undefined" || !member.card ? await e.group.pickMember(Number(qq)) : ''
            name = member?.card || member?.nickname || ''
            name = typeof name === "undefined" ? await getname(qq) : name.trim() ? name : await getname(qq)
            return name
        }))
    } catch {
        names = typeof nums !== "undefined" && Array.isArray(nums) && nums.length > 0 ? names.concat(nums) : names
    } finally {
        str = Array.isArray(names) ? str.replace(/(AAAA)/g, () => names[index++ % names.length]) : str
    }
    str = str.slice(1, -1)
    return str
}


export async function getStatus(res) {
    let symbols = Object.getOwnPropertySymbols(res)
    let internals = res[symbols[0]]
    let status = internals.status
    return status
}

export async function modifyText(res, e) {
    res = await res.text()
    let str = res
    str = await fix(str, e)
    return str
}

async function getname(qq) {
    try {
        let response = await Bot.getStrangerInfo(qq)
        return response.nickname
    } catch {
        return qq
    }
}